import os
from dotenv import load_dotenv
from openai import OpenAI
from loguru import logger

# 加载环境变量
load_dotenv()

class DeepSeekAPIDemo:
    def __init__(self):
        self._validate_api_key()
        self.client = OpenAI(api_key=os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com/v1")

    def _validate_api_key(self):
        """验证API密钥有效性"""
        api_key = os.getenv('DEEPSEEK_API_KEY')
        if not api_key or api_key == 'your_api_key_here' or len(api_key) < 32:
            raise ValueError("无效的DeepSeek API密钥，请检查.env文件配置")

    def get_response(self, prompt):
        """获取模型响应"""
        try:
            response = self.client.chat.completions.create(
                model="deepseek-chat",
                messages=[{"role": "user", "content": prompt}],
                temperature=0,
                max_tokens=2000
            )
            return response.choices[0].message.content
        except Exception as e:
            logger.error(f"API调用失败: {str(e)}")
            raise RuntimeError(f"API请求异常: {str(e)}") from e

if __name__ == "__main__":
    try:
        demo = DeepSeekAPIDemo()
        response = demo.get_response("请简要说明孕期营养补充的注意事项")
        print("模型响应：", response)
    except Exception as e:
        print(f"程序异常: {str(e)}")